package cn.stronglink.assetmanage.business.setting;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.entity.ServerIp;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.netrequest.util.HttpURL;

/**
 * A simple {@link Fragment} subclass.
 */
public class SystemServerConfigFragment extends Fragment {
    private Unbinder mUnbinder;
    @BindView(R.id.imgIp)
    ImageView imgIp;
    @BindView(R.id.etServerIp)
    EditText etServerIp;
    @BindView(R.id.txtServerTips)
    TextView txtServerTips;
    @BindView(R.id.btnSetServer)
    Button btnSetServer;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_system_server_config, container, false);
        mUnbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (DaoManager.getDaoSession(getContext()).getServerIpDao().queryBuilder().count() > 0) {
            etServerIp.setText(DaoManager.getDaoSession(getContext()).getServerIpDao().queryBuilder().unique().getIpAddress());
        } else {
            etServerIp.setText(HttpURL.getHost());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    @OnClick(R.id.btnSetServer)
    public void btnServer() {
        String ipStr = etServerIp.getText().toString();
        if (ipStr != null && !"".equals(ipStr)) {
            DaoManager.getDaoSession(getContext()).getServerIpDao().deleteAll();
            ServerIp ip = new ServerIp();
            ip.setIpAddress(ipStr);
            DaoManager.getDaoSession(getContext()).getServerIpDao().insert(ip);
            ipSet();
            ToastUtil.toastShort("地址设置成功!");
        } else {
            txtServerTips.setText("输入IP有误,请重新输入!");
        }
    }

    private void ipSet() {
        if (DaoManager.getDaoSession(getContext()).getServerIpDao().queryBuilder().count() > 0) {
            HttpURL.setNewHost(DaoManager.getDaoSession(getContext()).getServerIpDao().queryBuilder().unique().getIpAddress());
        }
    }
}
